package com.atguigu.chapter11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Over;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;
import java.time.ZoneOffset;

import static org.apache.flink.table.api.Expressions.*;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/24 10:03
 */
public class Flink12_Table_Window_Over {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        tenv.getConfig().setLocalTimeZone(ZoneOffset.ofHours(0));
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env
            .fromElements(new WaterSensor("sensor_1", 1000L, 10),
                          new WaterSensor("sensor_1", 2000L, 20),
                          new WaterSensor("sensor_1", 2000L, 30),
                          new WaterSensor("sensor_1", 3000L, 40),
                          new WaterSensor("sensor_1", 5000L, 50)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
            );
        
        Table table = tenv.fromDataStream(waterSensorStream, $("id"), $("ts").rowtime().as("et"), $("vc"));
        
        // 每条数据后面新增一个字段, 用来记录当前这个sensor的水位和
        // sum(vc) over(partition by id order by count desc rows between 1 preceding row and current row) sum_vc
        // 注意: 如果不是在做topN,则over中orderBy只能是时间字段的升序
        table
//            .window(Over.partitionBy($("id")).orderBy($("et")).preceding(UNBOUNDED_ROW).as("w"))
            //            .window(Over.partitionBy($("id")).orderBy($("et")).preceding(rowInterval(1L)).as("w"))
//            .window(Over.partitionBy($("id")).orderBy($("et")).preceding(UNBOUNDED_RANGE).as("w"))
            .window(Over.partitionBy($("id")).orderBy($("et")).preceding(lit(1).second()).as("w"))
            .select($("id"), $("et"), $("vc"), $("vc").sum().over($("w")).as("sum_vc"))
            .execute()
            .print();
        
    }
}
